<template>
  <el-dialog
    :title="formData.ID ? '编辑物料' : '新增物料'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="600px"
    :before-close="handleClose"
     draggable >
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px">
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料编码" prop="materCode">
            <el-input
              v-model="formData.materCode"
              placeholder="请输入物料编码"
              :disabled="!!formData.ID" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="materName">
            <el-input
              v-model="formData.materName"
              placeholder="请输入物料名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料类型" prop="materTepyName">
            <el-select
              v-model="formData.materTepyName"
              placeholder="请选择物料类型"
              style="width: 100%"
              clearable
              filterable
              @change="handleTepyChange"
            >
              <el-option
                v-for="item in MaterTypeOptions"
                :key="item.id"
                :label="item.mT_Name"
                :value="item.mT_Name"
              />
            </el-select>
            <el-input
              v-model="formData.materTepyID"
              placeholder="请输入供应商"
              type="text" v-if="false" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="10">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input
              v-model="formData.unit"
              placeholder="请输入单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标准成本" prop="standardCost">
            <el-input
              v-model="formData.standardCost"
              placeholder="请输入标准成本"
              type="number"
              step="0.01">
              <template #prefix>¥</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="补货点" prop="reorderPoint">
            <el-input
              v-model="formData.reorderPoint"
              placeholder="请输入补货点"
              type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierName">
            <el-select
              v-model="formData.supplierName"
              placeholder="请选择供应商"
              style="width: 100%"
              clearable
              filterable
              @change="handleSuppChange"
            >
              <el-option
                v-for="item in materOptions"
                :key="item.id"
                :label="item.suName"
                :value="item.suName"
              />
            </el-select>
            <el-input
              v-model="formData.supplierID"
              placeholder="请输入供应商"
              type="text" v-if="false" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit />
      </el-form-item> -->
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ formData.ID ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { request } from '@/utils/request'

// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  }
})

// 定义 emits
const emit = defineEmits(['update:visible', 'submit', 'close'])

// 响应式数据
const loading = ref(false)
const formRef = ref()
const materOptions = ref([]) // 物料选项列表
const MaterTypeOptions = ref([]) // 物料类型列表
// 表单验证规则
const formRules = {
  materCode: [
    { required: true, message: '请输入物料编码', trigger: 'blur' },
    { min: 1, max: 50, message: '物料编码长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  materName: [
    { required: true, message: '请输入物料名称', trigger: 'blur' },
    { min: 1, max: 100, message: '物料名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  materTepyID: [
    { required: true, message: '请选择物料类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  standardCost: [
    { required: true, message: '请输入标准成本', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ],
  reorderPoint: [
    { required: true, message: '请输入补货点', trigger: 'blur' },
    // { pattern: /^\d+$/, message: '补货点必须为整数', trigger: 'blur' }
  ],
  supplierName: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ]
}

// 监听 visible 变化，重置表单验证
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    })
    // 打开弹窗时加载物料列表
    loadMaterList()
    loadMatertypeList()
  }
})
// 加载供应商列表
const loadMaterList = async () => {
  try {
    const response = await request.get('/Supplier')
    materOptions.value = response || []
  } catch (error) {
    ElMessage.error('加载供应商列表失败')
    materOptions.value = []
  }
}
// 加载物料类型列表
const loadMatertypeList = async () => {
  try {
    const response = await request.get('/MaterType')
    MaterTypeOptions.value = response || []
  } catch (error) {
    ElMessage.error('加载物料列表失败')
    MaterTypeOptions.value = []
  }
}
//供应商选择变化处理
const handleSuppChange = (value) => {
  const selectedMater = materOptions.value.find(item => item.suName === value)
  if (selectedMater) {
    // 自动填充供应商编码
    props.formData.supplierID = selectedMater.MT_Code
  }else{
    props.formData.supplierID=''
    props.formData.supplierName=''
  }
}
//物料选择变化处理
const handleTepyChange = (value) => {
  const selectedMater = MaterTypeOptions.value.find(item => item.mT_Name === value)
  if (selectedMater) {
    // 自动填充物料类型编码
    props.formData.materTepyID = selectedMater.SuCode
  }else{
    props.formData.materTepyID=''
    props.formData.materTepyName=''
  }
}
// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true
    
    // 触发提交事件，传递表单数据
    emit('submit', { ...props.formData })
    
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    }
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  setLoading: (value) => {
    loading.value = value
  }
})
</script>

<style scoped>
/* 弹窗样式优化 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>